package com.weijx.dishes.service.impl;
import com.weijx.dishes.config.FrontendConfig;
import com.weijx.dishes.entity.Order;
import com.weijx.dishes.entity.OrderDetail;
import com.weijx.dishes.service.EmailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.mail.MessagingException;
/**
 * com.weijx.dishes.service.impl.EmailServiceImpl
 * 描述：
 * on 2025/10/24-下午3:44
 *
 * @author weijx
 */


@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Resource
    private FrontendConfig frontendConfig;

    @Override
    @Async
    public void sendOrderNotificationToMe(Order order) {
        String processUrl = frontendConfig.getProcessUrl(order.getId());
        String subject = "🍽️ 点餐通知 - " + order.getCustomerName() + "下单了！";
        String content = buildOrderNotificationEmail(order, processUrl);
        sendHtmlEmail("wei77iverson@163.com", subject, content);
    }

    @Override
    @Async
    public void sendProcessResultToGirlfriend(Order order) {
        String subject = "🍽️ 订单处理结果 - 订单ID:" + order.getId();
        String content = buildProcessResultEmail(order);
        sendHtmlEmail("wei77iverson@163.com", subject, content);
    }


    private void sendHtmlEmail(String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送失败: " + e.getMessage(), e);
        }
    }

    private String buildOrderNotificationEmail(Order order, String processUrl) {
        // 构建订单详情HTML
        StringBuilder itemsHtml = new StringBuilder();
        if (order.getOrderDetails() != null) {
            for (OrderDetail detail : order.getOrderDetails()) {
                itemsHtml.append("<tr>")
                        .append("<td>").append(detail.getProductName()).append("</td>")
                        .append("<td>").append(detail.getQuantity()).append("</td>")
                        .append("</tr>");
            }
        }


        return "<!DOCTYPE html>" +
                "<html>" +
                "<head>" +
                "<meta charset=\"UTF-8\">" +
                "<style>" +
                "body { font-family: 'Microsoft YaHei', sans-serif; color: #333; line-height: 1.6; }" +
                ".container { max-width: 600px; margin: 0 auto; padding: 20px; border: 2px solid #ff6b6b; border-radius: 10px; }" +
                ".header { background: linear-gradient(135deg, #ff6b6b, #ff8e8e); color: white; padding: 20px; text-align: center; border-radius: 8px; margin-bottom: 20px; }" +
                ".order-info { background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px; }" +
                ".items-table { width: 100%; border-collapse: collapse; margin: 15px 0; }" +
                ".items-table th, .items-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }" +
                ".items-table th { background: #f2f2f2; }" +
                ".btn { display: inline-block; background: #ff6b6b; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; margin: 10px 0; }" +
                ".footer { text-align: center; margin-top: 20px; color: #666; font-size: 14px; }" +
                "</style>" +
                "</head>" +
                "<body>" +
                "<div class=\"container\">" +
                "<div class=\"header\">" +
                "<h1>🍽️ 点餐通知</h1>" +
                "<p>亲爱的，" + order.getCustomerName() + " 刚刚下单啦！快去准备吧~</p>" +
                "</div>" +
                "<div class=\"order-info\">" +
                "<h3>📋 订单信息</h3>" +
                "<p><strong>订单ID：</strong>" + order.getId() + "</p>" +
                "<p><strong>客户姓名：</strong>" + order.getCustomerName() + "</p>" +
                "<p><strong>备注：</strong>" + (order.getNote() != null ? order.getNote() : "无") + "</p>" +
                "<h4>🛒 订单内容</h4>" +
                "<table class=\"items-table\">" +
                "<thead><tr><th>餐品名称</th><th>数量</th></tr></thead>" +
                "<tbody>" +
                itemsHtml.toString() +
                "</tbody>" +
                "</table>" +
                "</div>" +
                "<div style=\"text-align: center;\">" +
                "<a href=\"" + processUrl + "\" class=\"btn\">📝 立即处理订单</a>" +
                "</div>" +
                "<div class=\"footer\">" +
                "<p>这是一封自动通知邮件，请及时处理哦！💖</p>" +
                "</div>" +
                "</div>" +
                "</body>" +
                "</html>";
    }

    private String buildProcessResultEmail(Order order) {
        String statusText = "";
        String statusColor = "";
        if (order.getOrderStatus() == 1) {
            statusText = "✅ 已完成";
            statusColor = "#52c41a";
        } else if (order.getOrderStatus() == 2) {
            statusText = "❌ 已驳回";
            statusColor = "#ff4d4f";
        }


        return "<!DOCTYPE html>" +
                "<html>" +
                "<head>" +
                "<meta charset=\"UTF-8\">" +
                "<style>" +
                "body { font-family: 'Microsoft YaHei', sans-serif; color: #333; line-height: 1.6; }" +
                ".container { max-width: 600px; margin: 0 auto; padding: 20px; border: 2px solid #52c41a; border-radius: 10px; }" +
                ".header { background: linear-gradient(135deg, #52c41a, #73d13d); color: white; padding: 20px; text-align: center; border-radius: 8px; margin-bottom: 20px; }" +
                ".order-info { background: #f8f9fa; padding: 15px; border-radius: 8px; }" +
                ".footer { text-align: center; margin-top: 20px; color: #666; font-size: 14px; }" +
                "</style>" +
                "</head>" +
                "<body>" +
                "<div class=\"container\">" +
                "<div class=\"header\">" +
                "<h1>🍽️ 订单处理结果</h1>" +
                "<p>亲爱的 " + order.getCustomerName() + "，你的订单已处理完成</p>" +
                "</div>" +
                "<div class=\"order-info\">" +
                "<h3>📋 处理结果</h3>" +
                "<p><strong>订单ID：</strong>" + order.getId() + "</p>" +
                "<p><strong>处理状态：</strong><span style=\"color:" + statusColor + "; font-weight:bold;\">" + statusText + "</span></p>" +
                "<p><strong>处理备注：</strong>" + (order.getProcessNote() != null ? order.getProcessNote() : "无") + "</p>" +
                "</div>" +
                "<div class=\"footer\">" +
                "<p>感谢你的使用！如有问题请联系我哦~ 💖</p>" +
                "</div>" +
                "</div>" +
                "</body>" +
                "</html>";
    }
}